﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Data
{
    /// <summary>
    /// 界面中所有节点信息保存
    /// </summary>
    static class RequestParameteDataSave
    {
        /// <summary>
        /// 保存节点 
        /// </summary>
        /// <param name="ID">来源与itemslist的Node</param>
        public static void setSave(String ID, RequestParameteData pnd)
        {
            string thisExeDirectory = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string thisDirectory = thisExeDirectory + @"JSONData" + "\\JSONDataList";
            if (!Directory.Exists(thisDirectory))
            {
                Directory.CreateDirectory(thisDirectory);
            }
            //版本
            string VerDirectory = thisExeDirectory + @"JSONData" + "\\JSONDataList\\" + ID;
            if (!Directory.Exists(VerDirectory))
            {
                Directory.CreateDirectory(VerDirectory);
            }

            //保存节点
            string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string thisFile = VerDirectory + @"\\" + pnd.requestVersion + @".json";
            using (StreamWriter file = File.CreateText(thisFile))
            {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                serializer.Serialize(file, pnd);
            }
        }

        /// <summary>
        /// 复制节点文件
        /// </summary>
        /// <param name="OID"></param>
        /// <param name="NID"></param>
        public static void setCopy(String OID, String NID)
        {
            string thisExeDirectory = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            //版本
            string OVerDirectory = thisExeDirectory + @"JSONData" + "\\JSONDataList\\" + OID;
            string NVerDirectory = thisExeDirectory + @"JSONData" + "\\JSONDataList\\" + NID;
            if (Directory.Exists(OVerDirectory))
            {
                Directory.CreateDirectory(NVerDirectory);
                string[] files = Directory.GetFiles(OVerDirectory);
                foreach (string formFileName in files)
                {
                    string fileName = Path.GetFileName(formFileName);
                    string fromFileName = Path.Combine(OVerDirectory, fileName);
                    string toFileName = Path.Combine(NVerDirectory, fileName);
                    File.Copy(fromFileName, toFileName, true);
                }

            }
        }

        /// <summary>
        /// 加载保存
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public static RequestParameteData getSave(String ID, int Version)
        {
            string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string thisFile = thisExeFile + @"JSONData" + "\\JSONDataList\\" + ID + "\\" + Version.ToString() + ".json";
            if (File.Exists(thisFile))
            {
                using (StreamReader file = File.OpenText(thisFile))
                {
                    Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                    RequestParameteData NodeDatalist = (RequestParameteData)serializer.Deserialize(file, typeof(RequestParameteData));
                    return NodeDatalist;
                }
            }
            else
            {
                /* 创建新版本
                *RequestParameteData rpd = new RequestParameteData();
                *rpd.requestHeads = _requestHeads_default;
                *rpd.requestVersion = Version;
                *rpd.requestCode = @"主入口文件
function Main() {
    return ""New Tab"";
};";
                *return rpd;
                 */
                string thisFileve = thisExeFile + @"JSONData" + "\\JSONDataList\\" + ID + "\\" + 1 + ".json";
                using (StreamReader file = File.OpenText(thisFileve))
                {
                    Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                    RequestParameteData NodeDatalist = (RequestParameteData)serializer.Deserialize(file, typeof(RequestParameteData));
                    //切换版本
                    NodeDatalist.requestVersion = Version;
                    return NodeDatalist;
                }
            }
        }

        #region 存储所有Heads默认
        /// <summary>
        /// 存储所有Heads默认
        /// </summary>
        public static List<ParameterItemNodeData> _requestHeads_default = new List<ParameterItemNodeData>() { 
            new ParameterItemNodeData(){
                    Key = "Accept",
                    Value = "text/html, application/xhtml+xml, */*",
                    Remark = "接受类型",
                    Type = "SystemHeads",
                    Parameter = "",
                    ID = GUID.getGUID(),
                    ParentID = "",
            },
            new ParameterItemNodeData(){
                    Key = "ContentType",
                    Value = "application/x-www-form-urlencoded",
                    Remark = "内容类型",
                    Type = "SystemHeads",
                    Parameter = "",
                    ID = GUID.getGUID(),
                    ParentID = "",
            },
            new ParameterItemNodeData(){
                    Key = "Encoding",
                    Value = "UTF-8",
                    Remark = "编码方式-只支持UTF-8",
                    Type = "SystemHeads",
                    Parameter = "",
                    ID = GUID.getGUID(),
                    ParentID = "",
            },
            new ParameterItemNodeData(){
                    Key = "Method",
                    Value = "POST",
                    Remark = "请求方式:GET、POST",
                    Type = "SystemHeads",
                    Parameter = "",
                    ID = GUID.getGUID(),
                    ParentID = "",
            },
            new ParameterItemNodeData(){
                    Key = "ProtocolVersion",
                    Value = "HTTP/1.1",
                    Remark = "HTTP版本",
                    Type = "SystemHeads",
                    Parameter = "",
                    ID = GUID.getGUID(),
                    ParentID = "",
            },
            new ParameterItemNodeData(){
                    Key = "Referer",
                    Value = "http://www.localhost.com",
                    Remark = "请求来源",
                    Type = "SystemHeads",
                    Parameter = "",
                    ID = GUID.getGUID(),
                    ParentID = "",
            },
            new ParameterItemNodeData(){
                            Key = "UserAgent",
                            Value = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
                            Remark ="浏览器头标识",                            
                            Type = "SystemHeads",
                            ID = System.Guid.NewGuid().ToString(),
                            ParentID = "",
                        },
        };
        #endregion

        /// <summary>
        /// 导出-系统默认
        /// </summary>
        /// <param name="IDs"></param>
        /// <param name="part"></param>
        /// <param name="lrdd"></param>
        public static void setExport(List<string[]> IDs, string part, List<RequserDirectoryData> lrdd)
        {
            string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            //0= id 文件夹名称
            //1 = name
            foreach (string[] id in IDs)
            {
                string thisDirectory = thisExeFile + @"JSONData" + "\\JSONDataList\\" + id[0];
                if (Directory.Exists(thisDirectory))
                {
                    string newDirectory = part + "\\" + id[0];
                    Directory.CreateDirectory(newDirectory);
                    string[] files = Directory.GetFiles(thisDirectory);
                    foreach (string formFileName in files)
                    {
                        string fileName = Path.GetFileName(formFileName);
                        string fromFileName = Path.Combine(thisDirectory, fileName);
                        string toFileName = Path.Combine(newDirectory, fileName);
                        File.Copy(fromFileName, toFileName, true);
                    }
                    //保存节点
                    string thisFile = part + @"\\" + @"Export.json";
                    using (StreamWriter file = File.CreateText(thisFile))
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(file, lrdd);
                    }
                }
            }

        }

        /// <summary>
        /// 导入-系统默认
        /// </summary>
        /// <param name="sPath">导入文件的地址</param>
        /// <param name="thisFile"></param>
        /// <param name="parid"></param>
        public static List<RequserDirectoryData> getExport(string sPath, string thisFile, List<RequserDirectoryData> treeldd)
        {
            using (StreamReader file = File.OpenText(thisFile))
            {
                string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                List<RequserDirectoryData> NodeDatalist = (List<RequserDirectoryData>)serializer.Deserialize(file, typeof(List<RequserDirectoryData>));
                bool notall = true;
                List<string[]> IDs = new List<string[]>();
                foreach (RequserDirectoryData ndl in NodeDatalist)
                {
                    //id重复
                    RequserDirectoryData frdd = treeldd.Find(x=>x.ID == ndl.ID);
                    if (frdd != null) {
                        notall = false;
                        return null;
                    }
                    //文件不存在
                    if (!Directory.Exists(sPath + "\\" + ndl.ID))
                    {
                        if (ndl.type == "file")
                        {
                            notall = false;
                        }
                    }
                    else
                    {
                        IDs.Add(new string[] { ndl.ID, ndl.key });
                    }
                }
                if (notall)
                {
                    foreach (string[] id in IDs)
                    {
                        string thisDirectory = thisExeFile + @"JSONData" + "\\JSONDataList\\" + id[0];
                        if (Directory.Exists(thisDirectory))
                        {
                             return null;
                        }
                    }
                    foreach (string[] id in IDs)
                    {
                        string thisDirectory = thisExeFile + @"JSONData" + "\\JSONDataList\\" + id[0];
                        Directory.CreateDirectory(thisDirectory);
                        string[] files = Directory.GetFiles(sPath + "\\" + id[0]);
                        foreach (string formFileName in files)
                        {
                            string fileName = Path.GetFileName(formFileName);
                            string fromFileName = Path.Combine(sPath + "\\" + id[0], fileName);
                            string toFileName = Path.Combine(thisDirectory, fileName);
                            File.Copy(fromFileName, toFileName, true);
                        }
                        return NodeDatalist;
                    }
                }
                return null;
                //return NodeDatalist;
            }
        }
    }
}
